package com.spzx.payment.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.security.annotation.RequiresLogin;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/alipay")
public class AlipayController extends BaseController {

    @Autowired
    private IAlipayService alipayService;

    @Autowired
    private IPaymentInfoService paymentInfoService;

    @Operation(summary = "支付宝下单")
    @RequiresLogin
    @RequestMapping("submitAlipay/{orderNo}")
    @ResponseBody
    public AjaxResult submitAlipay(@PathVariable("orderNo") String orderNo) {
        String form = alipayService.submitAlipay(orderNo);
        return success(form);
    }

    /*@Operation(summary = "支付宝同步回调")
    @GetMapping("callback/return")
    public String callBack(){
        return "redirect:"+ AlipayConfig.return_payment_url;
    }
*/
    @Operation(summary = "支付宝异步回调")
    @RequestMapping("callback/notify")
    public String alipayNotify(@RequestParam Map<String, String> paramMap ,HttpServletRequest  request){
        log.info("AlipayController...alipayNotify方法执行了...");
        //1. 验签
        boolean signVerified = false;// 调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(paramMap, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        //2.更新支付信息-》更新订单状态-》减库存
        //支付宝验签成功并且支付成功后会把之前的参数返回给商户，验签成功后，按照支付结果异步通知中的描述，
        // 对支付结果中的业务内容进行二次校验，
        // 校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
        if (signVerified) {
            String trade_status = paramMap.get("trade_status");
            if ("TRADE_SUCCESS".equals(trade_status)|| "TRADE_FINISHED".equals(trade_status)){
                //支付成功 更新支付信息
                paymentInfoService.updatePaymentInfo(paramMap,2);
                return "success";
            }
        }else {
            log.error("支付宝异步回调签名验证失败...");
            return "failure";
        }
        return "failure";
    }
}